#include "font.h"

void Font::Init() {
    TTF_Init();
}

void Font::Shutdown() {
    TTF_Quit();
}

Font::Font(const std::string& ttf_path, int pt) {
    font_ = TTF_OpenFont(ttf_path.c_str(), pt);
    if (!font_) {

        printf("TTF Error: can't find %s\n", ttf_path.c_str());
    }
}

Font::~Font() {
    SDL_DestroyTexture(texture_);
    TTF_CloseFont(font_);
}

void Font::Draw(SDL_Renderer* render, const std::string& str, int x, int y, int w, int h) {
    SDL_Rect rect = {x, y, w, h};
    Draw(render, str, rect);
}

void Font::Draw(SDL_Renderer* render, const std::string& str, const SDL_Rect& rect) {
    SDL_Color color = {0, 0, 0, 255};
    if (text_ != str) {
        auto surface = TTF_RenderText_Blended(font_, str.c_str(), color);
        texture_ = SDL_CreateTextureFromSurface(render, surface);
        SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
        Clear(render);
        text_ = str;
        SDL_FreeSurface(surface);
    }
    SDL_RenderCopy(render, texture_, nullptr, &rect);
}

void Font::Clear(SDL_Renderer* render) {
    SDL_SetRenderTarget(render, texture_);
    SDL_SetRenderDrawColor(render, 0,0,0,0);
    SDL_RenderClear(render);
    SDL_SetRenderTarget(render, nullptr);
}
